package servlet;

import org.json.JSONArray;
import test.RatingMap;
import test.ReadResult;
import test.SaveLasted;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author IlseTian
 * @ 2020-07-01- 20:50
 **/
@WebServlet("/RatingServlet")
public class RatingServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决中文乱码
        response.setContentType("text/html;charset=utf-8");
        //请求解决乱码
        request.setCharacterEncoding("utf-8");
        //响应解决乱码
        response.setCharacterEncoding("utf-8");

        String movieID = request.getParameter("movieID");
        int size = SaveLasted.pathList.size();
        if (size != 0) {
            String filepath = SaveLasted.pathList.get(size - 1);
            ReadResult.readFile(filepath);

            if (RatingMap.ratings.containsKey(movieID)) {
                String rtg = RatingMap.ratings.get(movieID);
                String[] rs = rtg.split("@");
                String[] xdata = new String[rs.length];
                Double[] ydata = new Double[rs.length];

                for (int i = 0; i < rs.length; i++) {
                    String[] kv = rs[i].split("&");
                    xdata[i] = kv[0];
                    ydata[i] = Double.valueOf(kv[1]);
                }

                org.json.JSONArray jsonx = new org.json.JSONArray(xdata);
                org.json.JSONArray jsony = new JSONArray(ydata);
                System.out.println("xxxxxx@@@@@@@@@@@" + jsonx.toString());
                System.out.println("yyyyyy@@@@@@@@@@@" + jsony.toString());

                List<HashMap> list1 = new ArrayList<>();

                HashMap<String, Double[]> map0 = new HashMap<String, Double[]>();
                map0.put("yData", ydata);
                list1.add(map0);
                HashMap<String, String[]> map1 = new HashMap<String, String[]>();
                map1.put("xData", xdata);
                list1.add(map1);
                PrintWriter writer = response.getWriter();
                net.sf.json.JSONArray json = net.sf.json.JSONArray.fromObject(list1);
                writer.println(json);

            } else {
                System.out.println("暂无此电影评分");
            }
        }
        System.out.println("***************************");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

}
